﻿namespace EyeSoft.ServiceLocator.Windsor
{
	using System;
	using System.Collections.Generic;
	using System.Linq;

	using Castle.Windsor;

	using EyeSoft.ServiceLocator;

	public class WindsorDependencyContainer : DependencyContainer
	{
		protected readonly IWindsorContainer container;

		public WindsorDependencyContainer(bool throwExceptionOnMissingComponent = true)
			: this(new WindsorContainer(), throwExceptionOnMissingComponent)
		{
		}

		public WindsorDependencyContainer(IWindsorContainer container, bool throwExceptionOnMissingComponent = true)
			: base(throwExceptionOnMissingComponent)
		{
			this.container = container;
		}

		public IWindsorContainer Container
		{
			get
			{
				return container;
			}
		}

		public override object GetInstance(Type serviceType, IDictionary<string, object> parameters)
		{
			return container.Resolve(serviceType, new Dictionary<string, object>(parameters));
		}

		public override T GetInstance<T>(IDictionary<string, object> parameters)
		{
			return container.Resolve<T>(new Dictionary<string, object>(parameters));
		}

		public override void Release(object instance)
		{
			container.Release(instance);
		}

		public override void Dispose()
		{
			container.Dispose();
		}

		protected override object DoGetInstance(Type serviceType, string key)
		{
			if (key != null)
			{
				return container.Resolve(key, serviceType);
			}

			return container.Resolve(serviceType);
		}

		protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
		{
			return (object[])container.ResolveAll(serviceType);
		}

		protected override bool Any(Type serviceType)
		{
			return
				Container.Kernel.GetAssignableHandlers(serviceType).Any();
		}
	}
}